import cgi
import datetime
import urllib # encode url
import webapp2 # use with python27
import jinja2 # template system
import os # get file directory

from google.appengine.ext import db
from google.appengine.api import users

# initialize template 
jinja_environment = jinja2.Environment(
                    loader = jinja2.FileSystemLoader(os.path.dirname(__file__))
                                       )
class Greeting(db.Model):
    """Models an individual Guestbook entry with an author, content, and date."""
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

# Picture entity
class Picture(db.Model):
    url = db.StringProperty()
    title = db.StringProperty()
    like = db.IntegerProperty()
    dislike = db.IntegerProperty()

# Get key of object
def get_key(kind, object_name=None):
    return db.Key.from_path(kind, object_name or 'default_object_name')

# Save picture to datastore
class PictureUpload(webapp2.RequestHandler):
    def post(self):
        # set kind
        picture = Picture(parent=get_key('Picture', 'Nature'))
        
        # set values
        picture.url = self.request.get('picurl')
        picture.title = self.request.get('pictitle')
        
        picture.like = 0
        picture.dislike = 0
        
        # save
        picture.put()
        
        # get key and redirect to showpic page
        self.redirect('/showpic?' + urllib.urlencode({'pic': picture.key()}))

# Show picture
class PictureShow(webapp2.RequestHandler):
    def get(self):
        # get key (id)
        pic_id = self.request.get('pic')
        
        # get picture from datastore by its key
        picture = db.get(pic_id)
        
        # set template values
        template_values = {
                           'picture' : picture,
                           }
        template = jinja_environment.get_template('showpicture.html')
        
        # render template
        self.response.out.write(template.render(template_values))

# Get picture page
class PictureUploadTemplate(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('upload_picture.html')
        self.response.out.write(template.render())

# Handle like button
class PictureLike(webapp2.RequestHandler):
    def post(self):
        picture_key = self.request.get('key')
        picture = db.get(picture_key)
        
        picture.like += 1
        picture.put()

        self.response.out.write(picture.like)

# Handle dislike button
class PictureDislike(webapp2.RequestHandler):
    def post(self):
        picture_key = self.request.get('key')
        picture = db.get(picture_key)
        
        picture.dislike += 1
        picture.put()

        self.response.out.write(picture.dislike)
class MainPage(webapp2.RequestHandler):
    def get(self):
        '''
        guestbook_name=self.request.get('guestbook_name')
        greetings_query = Greeting.all().ancestor(
             get_key('Guestbook', guestbook_name)).order('-date')
        greetings = greetings_query.fetch(10)
        '''
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
        
        pictures_query = Picture.all().ancestor(get_key('Picture', 'Nature'))
        pictures = pictures_query.fetch(10)
        
        template_values = {
            #'greetings': greetings,
            'pictures': pictures,
            'url': url,
            'url_linktext': url_linktext,           
                       }
        template = jinja_environment.get_template('index.html')
    
        self.response.out.write(template.render(template_values))

class Guestbook(webapp2.RequestHandler):
    def post(self):
    # We set the same parent key on the 'Greeting' to ensure each greeting is in
    # the same entity group. Queries across the single entity group will be
    # consistent. However, the write rate to a single entity group should
    # be limited to ~1/second.
        guestbook_name = self.request.get('guestbook_name')
        greeting = Greeting(parent=get_key('Guestbook', guestbook_name))

        if users.get_current_user():
            greeting.author = users.get_current_user()

        greeting.content = self.request.get('content')
        greeting.put()
        self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))


app = webapp2.WSGIApplication([('/', MainPage),
                               ('/sign', Guestbook),
                               ('/addpic', PictureUpload),
                               ('/add', PictureUploadTemplate),
                               ('/showpic', PictureShow),
                               ('/like', PictureLike),
                               ('/dislike', PictureDislike),
                               ],
                              debug=True)